package com.example.onlinemusic.controller;

import com.example.onlinemusic.common.Constant;
import com.example.onlinemusic.common.ResponseBodyMessage;
import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/music")
public class MusicController {
    @Value("${music.local.path}")
    private String SAVA_PATH;
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private LoveMusicMapper loveMusicMapper;

    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam MultipartFile file,
                                                    HttpServletRequest request,
                                                    HttpServletResponse resp){
        // 1. 检查是否登录了
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USER_SESSION_KEY) == null){
            System.out.println("没有登录！");
            return new ResponseBodyMessage<>(-1,"请登录后上传！",false);
        }

        // 2. 查询数据库里有没有当前音乐【歌曲名+歌手】
        String fileNameAndType = file.getOriginalFilename(); // 形如 xxx.mp3
        int index = fileNameAndType.lastIndexOf(".");
        String title = fileNameAndType.substring(0,index);

        Music music = musicMapper.check(title,singer);
        if(music != null){
            System.out.println("当前已有该音乐了，无需添加");
            return new ResponseBodyMessage<>(-1,"无需继续上传！",false);
        }

        // 3. 上传到服务器

        System.out.println("fileNameAndType:"+fileNameAndType);
        String path = SAVA_PATH +fileNameAndType;
        File dest = new File(path);
        if(!dest.exists()){
            dest.mkdir();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1,"服务器上传失败！",false);
        }

        // 进行数据库上传
        // 1. 准备数据   2. 调用 insert

        User user = (User)session.getAttribute(Constant.USER_SESSION_KEY);
        int userid = user.getId();

        // 1. 播放音乐 -> http 请求
        String url = "/music/get?path="+title;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sf.format(new Date());
            try {
                int ret = 0;
                ret = musicMapper.insert(title, singer, time, url, userid);
                if (ret == 1) {
                    // 跳转到音乐列表页
                     resp.sendRedirect("/list.html");
                    return new ResponseBodyMessage<>(1,"数据库上传成功！",true);
                } else {
                    return new ResponseBodyMessage<>(-1,"数据库上传失败！",false);
                }
            }catch (BindingException | IOException e) {
                dest.delete();
                e.printStackTrace();
                return new ResponseBodyMessage<>(-1,"数据库上传失败！",false);
            }
    }

    /**
     * 播放音乐时：/music/get?path=xxx.mp3
     * @param path
     * @return
     */
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path){
        File file = new File(SAVA_PATH+path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if(a == null){
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }

    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id){
        // 1. 先检查这个音乐是否存在？
        int iid = Integer.parseInt(id);
        // 2.如果存在，则进行删除
        Music music = musicMapper.findMusicById(iid);
        if (music == null){
            System.out.println("没有这个 id 的音乐");
            return new ResponseBodyMessage<>(-1,"没有要删除的音乐",false);
        }else {
            // 2.1 删除数据库上的数据
            int ret = musicMapper.deleteMusicById(iid);
            if(ret == 1){
                // 2.2 删除服务器上的数据
                int index = music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index + 1);

                File file = new File(SAVA_PATH+fileName+".mp3");
                System.out.println("当前的路径："+file.getPath());

                if (file.delete()){
                    // 同步删除 lovemusic 表中的这个音乐
                    loveMusicMapper.deleteLoveMusicByMusicId(iid);
                    return new ResponseBodyMessage<>(1,"删除成功！",true);
                }else{
                    return new ResponseBodyMessage<>(-1,"服务器当中的音乐删除失败！",false);
                }
            }else{
                return new ResponseBodyMessage<>(-1,"数据库当中的音乐没有删除成功！",false);
            }
        }
    }

    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id ){
        System.out.println("所有的 ID："+id);
        int sum = 0;
        for (int i = 0; i < id.size(); i++){
            int musicId = id.get(i);
            Music music = musicMapper.findMusicById(musicId);
            if (music == null){
                System.out.println("没有这个 id 的曲目");
                return new ResponseBodyMessage<>(-1,"没有要删除的音乐",false);
            }
            // 2.1 删除服务器上的数据
            int ret = musicMapper.deleteMusicById(musicId);
            if(ret == 1){
                //2.2 删除服务器上的数据
                int index = music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index + 1);

                File file = new File(SAVA_PATH+fileName+".mp3");
                System.out.println("当前的路径："+file.getPath());

                if (file.delete()){
                    // 同步删除 lovemusic 表中的这个音乐
                    loveMusicMapper.deleteLoveMusicByMusicId(musicId);
                    sum += ret;
                }else{
                    return new ResponseBodyMessage<>(-1,"服务器当中的音乐删除失败！",false);
                }
            }else{
                return new ResponseBodyMessage<>(-1,"数据库当中的音乐没有删除成功！",false);
            }
        }
        if (sum == id.size()){
            System.out.println("整体删除成功！");
            return new ResponseBodyMessage<>(1,"音乐删除成功！",true);
        }else{
            System.out.println("整体删除失败！");
            return new ResponseBodyMessage<>(-1,"音乐删除失败！",false);
        }
    }

    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName){
        List<Music> musicList = null;
        if (musicName != null){
            musicList = musicMapper.findMusicByName(musicName);
        }else{
            musicList = musicMapper.findMusic();
        }

        return new ResponseBodyMessage<>(1,"查询到了所有的音乐！",musicList);
    }
}
